/**
 * Grunt init script file.
 * @param grunt
 */

module.exports = function (grunt) {

    grunt.emmet=function(){
        this.finalEmmetStr='';
        this.singleFinalEmmetStr='';
        this.finalLayoutSass='';
        this.singleLayoutSass='';
        this.copyconfig={};
        this.jsonconfig={};
        this.init=function(config){
            var keyreg=/^([a-z]+)(\d)$/i;
            var length=1;
            for(por in config){
                // console.log(config[por],por);
                var itemValue=config[por];
                var key=keyreg.exec(por);
                if(key&&key[1]=='con'){
                    // console.log('遍历带con前缀的json配置');
                    var nodeObj=itemValue;
                   this.generateSingleEmmet(nodeObj);
                   this.generateLayoutSass(nodeObj);
                   this.finalEmmetStr+= '.con.con'+length+'>.wrap>'+this.singleFinalEmmetStr+'\n';
                   this.finalLayoutSass+= '.con'+length+'{\n'+this.singleLayoutSass+'\n';
                   length++;
                   this.finalLayoutSass+= '}\n';
                }
                 
            }
            console.log(this.finalEmmetStr,'这是最终的emmet语句');
            // console.log(this.finalLayoutSass,'这是最终的scss语句');
        };
        // 计算一个object的属性个数
        this.objCount=function(o){
            var t = typeof o;
            if(t == 'string'){
                    return o.length;
            }else if(t == 'object'){
                    var n = 0;
                    for(var i in o){
                            n++;
                    }
                    return n;
            }
            return false;
        };

        // 以键值对存入一个对象中，类似队列，但是hashkey存在覆盖可能
        this.HashKey= function(){
            var data={};
            this.set=function(key,value){
                data[key]=value;
            }
            this.get=function(key){
                return data[key];
            }
        }
        // 检查数组中是否已存在该元素
        this.checkArr =function(arr,str){ 
            if(!arr.length) return true;
            for(var i=0;i<arr.length;i++){
                if(arr[i]==str) return false;
            }
            return true;
        }
        // 通过遍历节点列表找出某个元素的子节点
        this.getChildArr=function(arr,father){
            var childarr=[];
            for(var i=0;i<arr.length;i++){
                // if(father!='start'){
                //     console.log(arr[i][0],father,arr[i][0]==father);
                // }
                if(arr[i][0]===father&&this.checkArr(childarr,arr[i][1])){ 
                 childarr.push(arr[i][1]);
                }
            }
            // console.log(childarr);
            return childarr;
        }
        // 将一个数组转化为emmet
        this.transToEmmet=function(arr){
            var str='(';
            if(arr.length==1){
               str +='(.'+arr[0]+')';
            }else{
                for(var i=0;i<arr.length;i++){
                    str +=(i==0)?'':'+';
                    str +='(.'+arr[i]+')';
                }
            } 
            str+=')';
            return str;
        }
        // 获取每个con的emmet
        this.doEmmet=function(arr,initstr,nodelistarr){
             for(var j=0;j<arr.length;j++){
                var _childArr=this.getChildArr(nodelistarr,arr[j]);
                console.log('初始str:',initstr,'\n它的子元素数组:', _childArr,arr[j]);
                if(_childArr.length){
                    var _emmetStr=this.transToEmmet(_childArr);
                    // console.log(_emmetStr);
                    var reg="/(\\(."+arr[j]+")\\)/gi";
                    // eval(reg);
                    this.singleFinalEmmetStr=initstr.replace(eval(reg),'$1>'+_emmetStr+')');
                    console.log(_emmetStr,reg,this.singleFinalEmmetStr);
                    this.doEmmet(_childArr,this.singleFinalEmmetStr,nodelistarr);
                }
            }
        };
        
        // 获取单一conemmet 返回单一con得emmet
        this.generateSingleEmmet=function(nodeObj,pro){
            this.singleFinalEmmetStr='';
            var _tempNodeArr=[];
            var emmetStr='';
            var objlenth=this.objCount(nodeObj);
            for(node in nodeObj){
                var nodeValue;
                var nodeArr=[];
                nodeValue=nodeObj[node];
                nodeValue=nodeObj[node].split(',')[0]; 
                if(nodeValue.indexOf('>')){
                    nodeArr=nodeValue.split('>');
                }else{
                    nodeArr.push(nodeValue);
                }
                for(var i=0;i<nodeArr.length;i++){
                    // console.log(nodeArr,'arrshuju');
                    var _tempnode=[nodeArr[i-1]||'start',nodeArr[i],nodeArr[i+1]||'end'];
                    _tempNodeArr.push(_tempnode);
                }
                // console.log(_tempNodeArr);
            }
            var initArr=this.getChildArr(_tempNodeArr,'start');
            emmetStr+=this.transToEmmet(initArr);
            this.singleFinalEmmetStr=emmetStr;
            console.log(emmetStr,'init emmetStrS','init emmet');
             this.doEmmet(initArr,emmetStr,_tempNodeArr);
            return this.singleFinalEmmetStr;
        };
        // 获取layoutsass
      // 获取layoutsass
        this.generateLayoutSass =function(nodeObj){
            var initsass='';
            this.singleLayoutSass='';
            console.log('initsass','-------------');
            for(node in nodeObj){
                var nodeValue;
                console.log(node);
                nodeValue=nodeObj[node];
                nodeValue=nodeObj[node].split(','); 
                initsass+='\t.'+nodeValue[0]+'\t{\n\t\t@include wah('+nodeValue[1]+'px,'+nodeValue[2]+'px,none);\n\t}\n';
            }

            this.singleLayoutSass =initsass.replace(/>/g,' .');
        };

    };
    grunt.initConfig({
        pkg    : grunt.file.readJSON('package.json'),
        sass: {
          development: {
            options:{
                style:"compact",
                sourcemap:"none"
            }
          },
          initTemp:{
            options:{
                style:"compact"
            },
            files:[{
            }]
          }
        },
        watch  : {
            client :{
                files:["*/sass/*.scss","*/html/index.html"],
                tasks:['sass_run'],
                options:{
                    livereload:true,
                }
            }
        },
        copy:{
            main:{
                 expand:true,
                 cwd:'',
                 src:'',
                 dest:'',
            },
            js:{
                 expand:true,
                 src:'js/*',
            },
            images:{
                 expand:true,
                 src:'images/*',
            },
            tpl:{
                 expand:true,
                 src:'tpl/*',
            },
            html:{
                 expand:true,
                 src:'html/*',
            },
            sass:{
                 expand:true,
            },
        }
    });
    var emmetObj=new grunt.emmet();
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-css');
    grunt.loadNpmTasks('grunt-contrib-livereload');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.registerTask('copyAsset','handlerStaticResource',function(){
        grunt.config.merge({
            copy:{
                js:{
                    cwd:emmetObj.copyconfig.cwd,
                    dest:emmetObj.copyconfig.dest
                },
                images:{
                    cwd:emmetObj.copyconfig.cwd,
                    dest:emmetObj.copyconfig.dest    
                },
                sass:{
                    cwd:emmetObj.copyconfig.cwd,
                    src:'sass/*.scss',
                    dest:emmetObj.copyconfig.dest
                },
                tpl:{
                    cwd:emmetObj.copyconfig.cwd,
                    dest:emmetObj.copyconfig.dest
                },
                html:{
                    cwd:emmetObj.copyconfig.cwd,
                    dest:emmetObj.copyconfig.dest
                }
            }
        });
        grunt.task.run(['copy:js','copy:images','copy:sass','copy:tpl','copy:html']);
    });
    grunt.registerTask('copyIndexHtml','handlerStaticResource',function(){
          var HtmlHandleObj=function(content,config){
            this.content=content;
            this.config=config;
            this.changeTitle=function(){
                this.content=this.content.replace(/(<title>)(.+)(<\/title>)/g,'$1'+config.name+'$3'); 
            }
            this.changeCss=function(){
                this.content=this.content.replace(/(css\/)(.+)(\.css)/g,'$1'+config.date+'$3'); 
            }
            this.addEmmet=function(emmet){
                // console.log(emmet);
                 this.content=this.content.replace(/(EMMET)/g,""+emmet+""); 
            }
            // console.log(this.content.match(/(EMMET)/g));
        }
        grunt.config.merge({
            copy:{
                html:{
                    cwd:emmetObj.copyconfig.cwd,
                    src:'html/index.html',
                    dest:emmetObj.copyconfig.dest,
                    options:{
                        process:function(content,srcpath){
                            var hand1=new HtmlHandleObj(content,emmetObj.jsonconfig);
                            hand1.changeTitle();
                            hand1.changeCss();
                            hand1.addEmmet(emmetObj.finalEmmetStr);
                            return hand1.content;
                        }
                    }
                }
            }
        });
        grunt.task.run(['copy:html']);
    });
    grunt.registerTask('writeLayoutScss','writeLayoutScss',function(){
        var layoutScssPath=emmetObj.copyconfig.dest+'/sass/layout.scss';
        var newScssPath=emmetObj.copyconfig.dest+'/sass/'+emmetObj.jsonconfig.date+'.scss';
        var content= grunt.file.read(layoutScssPath);
        var newconent=content.replace(/\/\/SASS/g,emmetObj.finalLayoutSass);
        var fs =require('fs');
        fs.writeFileSync(newScssPath, newconent);
        fs.unlinkSync(layoutScssPath);
    });
    grunt.registerTask('initToBuild','initToBuild',function(date){
        var _date=new Date();
        var dir=date+'_'+_date.getTime();
         grunt.config.merge({
            copy:{
                initToBuild:{
                    expand:true,
                    cwd:'initTemp/'+date+'/',
                    src:'**',
                    dest:'build/'+dir+'/'
                }
            }
        });
        grunt.task.run(['copy:initToBuild','mysass:'+dir+':'+date+'']);
    });
    grunt.registerTask('mysass', 'do a sass task',function(path,file){
       if(!path||!file){
             grunt.log.warn('参数缺失'); 
             return false;
        }else{
            var csssrc= 'build/'+path+'/css/'+file+'.css';
            var saccsrc= 'build/'+path+"/sass/"+file+".scss"; 
             grunt.config.set('sass.initTemp.src',saccsrc);
             grunt.config.set('sass.initTemp.dest',csssrc);
                          grunt.task.run('sass:initTemp');
        }
    });
    grunt.registerTask('build','myapp',function(type,jsonpath){
        // console.log('正在进行myapp.....');

        // 转换模板类型。判断。。。
        var _type=parseInt(type);
        if(_type===1){
            console.log('正在构建泽元站静态模板');
            // 设置lib
            emmetObj.copyconfig.cwd='lib/zeyuan/';
        }else if(_type===2){
            console.log('正在构建专题静态模板');
             emmetObj.copyconfig.cwd='lib/zhuanti/';
        }else if(_type===3){
            console.log('正在构建类型3');
        }else{
            grunt.log.warn('参数缺失');
            return false;
        }
        // 获取模板配置的json参数
        var configjsonpath=jsonpath;

        emmetObj.jsonconfig =grunt.file.readJSON('webjson/'+configjsonpath);
                emmetObj.init(emmetObj.jsonconfig);
        // console.log(typeof(config));
        emmetObj.copyconfig.dest='initTemp/'+emmetObj.jsonconfig.date;

        // grunt.task.run(['copyAsset','copyIndexHtml','writeLayoutScss','initToBuild:'+emmetObj.jsonconfig.date+'']);
    });

    // Load the plugin that provides the "uglify" task.
    // grunt.loadNpmTasks('grunt-template');
    // Default task(s).
    grunt.registerTask('default', ['temp:1']);

    grunt.registerTask("live","autoRunSass",function(arg){
        if(!arg){
             grunt.log.warn('参数缺失'); 
             return false;
        }else{
             grunt.config.merge({
                watch  : {
                    client :{
                        files:["build/"+arg+"/sass/*.scss","build/"+arg+"/html/*"],
                        tasks:['mysass:'+arg+':'+arg+''],
                        options:{
                            livereload:true
                        }
                    }
                }
            });
            grunt.loadNpmTasks('grunt-contrib-watch');
            grunt.task.run(['watch']);
        }
    });  
    grunt.registerTask('newsass', 'do a sass task',function(path,file){
       if(!path||!file){
             grunt.log.warn('参数缺失'); 
             return false;
        }else{
            var csssrc= 'more/'+path+'/css/'+file+'.css';
            var saccsrc= 'more/'+path+"/sass/"+file+".scss"; 
             grunt.config.set('sass.initTemp.src',saccsrc);
             grunt.config.set('sass.initTemp.dest',csssrc);
                          grunt.task.run('sass:initTemp');
        }
    });  
    grunt.registerTask("ppx","autoRunSass",function(arg){
         grunt.config.merge({
            watch  : {
                client :{
                    files:["more/"+arg+"/sass/*.scss","more/"+arg+"/html/*.html"],
                    tasks:['newsass:'+arg+':'+arg+''],
                    options:{
                        livereload:true
                    }
                }
            }
        });
        grunt.loadNpmTasks('grunt-contrib-watch');
        grunt.task.run(['watch']);
    });
    grunt.registerTask('arrayHand','for emmet',function(arg){
       var jsonObj =grunt.file.readJSON('webjson/'+arg);
       var pathlist=[];
       var nodelist=['L1',[]];
       for(var item in jsonObj){
        // console.log(item,item.indexOf("con"));
        if(item.indexOf("con")!=-1){
            pathlist.push(jsonObj[item]); 
        }
       }
       var conObj={}
       conObj=pathlist[1];
       // console.log(pathlist[0],pathlist,conObj);
       for(var item2 in conObj){
        var onepath=conObj[item2];
        var _temparr=onepath.split(",")[0].split(">");
        // console.log(_temparr);
        for(var i=0;i<_temparr.length;i++){
            var _lev1,_lev2,_lev3,_lev4,_lev5,_lev6,_lev7;
            // if(i>1&&nodelist[_lev1][_lev2][_lev3]!==undefined){
            //     console.log(nodelist[_lev1][_lev2][_lev3],"执行完第"+i+"判断");
               
            // }
            // console.log("执行完")
            if(i==0){
                var _arrlength=nodelist.length;
                var _isnew=true;
                // console.log(_arrlength);
                for(var j=0;j<_arrlength;j++){
                    // console.log(nodelist[j*2]==undefined,_temparr[0]);
                    if(nodelist[j*2]==_temparr[i]){
                        _lev1=j*2+1;_isnew=false;break;
                    }
                };
                if(_isnew){
                        nodelist.push(_temparr[i]); 
                        nodelist.push([]); 
                };
            }else if(i==1){
                if(nodelist[_lev1].length==0){
                    var empty=[];
                   nodelist[_lev1].push(_temparr[i]);  
                  // if(i<_temparr.length-1)
                    nodelist[_lev1].push([]);  
                }
                var _arrlength=nodelist[_lev1].length;
                var _isnew=true;
                for(var k=0;k<_arrlength;k++){
                    if(nodelist[_lev1][k*2]==_temparr[i]){
                        _lev2=k*2+1; _isnew=false;break;
                    }
                };
                if(_isnew){
                        nodelist[_lev1].push(_temparr[i]); 
                       // if(i<_temparr.length-1)
                        nodelist[_lev1].push([]); 
                }
            }else if(i==2){
                if(nodelist[_lev1][_lev2].length==0){
                    var empty=[];
                   nodelist[_lev1][_lev2].push(_temparr[i]); 
                   // if(i<_temparr.length-1)
                     nodelist[_lev1][_lev2].push([]); 
                   
                }
                var _arrlength=nodelist[_lev1][_lev2].length;
                var _isnew=true;
                for(var k=0;k<_arrlength;k++){
                    if(nodelist[_lev1][_lev2][k*2]==_temparr[i]){
                        _lev3=k*2+1; _isnew=false;break;
                    }
                };
                if(_isnew){
                    // console.log(nodelist,typeof(nodelist),i,_lev2,_lev1);
                        nodelist[_lev1][_lev2].push(_temparr[i]); 
                      // if(i<_temparr.length-1)
                        nodelist[_lev1][_lev2].push([]); 
                }
                 // console.log(nodelist,'第3次迭代的数组');
            }else if(i==3){
                // console.log(nodelist[_lev1][_lev2][_lev3],"第三层级初始判断");
                if(nodelist[_lev1][_lev2][_lev3].length==0){
                    var empty=[];
                   nodelist[_lev1][_lev2][_lev3].push(_temparr[i]);  
                  // if(i<_temparr.length-1)
                    nodelist[_lev1][_lev2][_lev3].push([]); 
                    // console.log(nodelist[_lev1][_lev2][_lev3],'第三层级推入初始元素'); 
                }
                var _arrlength=nodelist[_lev1][_lev2][_lev3].length;
                var _isnew=true;
                // console.log(_arrlength);
                for(var l=0;l<_arrlength;l++){
                    if(nodelist[_lev1][_lev2][_lev3][l*2]==_temparr[i]){
                        _lev4=l*2+1; _isnew=false;break;
                    }
                };
                if(_isnew){
                    // console.log(nodelist,typeof(nodelist),i,_lev2,_lev1);
                        nodelist[_lev1][_lev2][_lev3].push(_temparr[i]); 
                      // if(i<_temparr.length-1)
                        nodelist[_lev1][_lev2][_lev3].push([]); 
                        // console.log(nodelist[_lev1][_lev2][_lev3],"第三判断存在新元素");
                }
            }else if(i==4){
                if(nodelist[_lev1][_lev2][_lev3][_lev4].length==0){
                    var empty=[];
                   nodelist[_lev1][_lev2][_lev3][_lev4].push(_temparr[i]);  
                  // if(i<_temparr.length-1)
                    nodelist[_lev1][_lev2][_lev3][_lev4].push([]);
                     // console.log(nodelist[_lev1][_lev2][_lev3],'第四层级推入初始元素');   
                }
                var _arrlength=nodelist[_lev1][_lev2][_lev3][_lev4].length;
                var _isnew=true;
                // console.log(_arrlength);
                for(var l=0;l<_arrlength;l++){
                    if(nodelist[_lev1][_lev2][_lev3][_lev4][l*2]==_temparr[i]){
                        _lev5=l*2+1; _isnew=false;break;
                    }
                };
                if(_isnew){
                    console.log();
                        nodelist[_lev1][_lev2][_lev3][_lev4].push(_temparr[i]); 
                      // if(i<_temparr.length-1)
                       nodelist[_lev1][_lev2][_lev3][_lev4].push([]); 
                }
            } 
            // console.log(nodelist,'最后的数组');
        }

       }
       
       var onepathlist=[];
       for(var i=0;i<nodelist.length;i++){
         if(i%2==0){
             console.log("1及栏目公有"+nodelist.length/2+'节点','节点名称',nodelist[i]);  
            for(var j=0;j<nodelist[i+1].length;j++){
                if(j%2==0){
                    console.log("2级栏目公有"+nodelist[i+1].length/2+'节点','节点名称',nodelist[i+1][j]);         
                    for(var k=0;k<nodelist[i+1][j+1].length;k++){
                        if(k%2==0){
                            console.log("3级栏目公有"+nodelist[i+1][j+1].length/2+'节点','节点名称',nodelist[i+1][j+1][k]);         
                            for(var l=0;l<nodelist[i+1][j+1][k+1].length;l++){
                                if(l%2==0){
                                    console.log("4级栏目公有"+nodelist[i+1][j+1][k+1].length/2+'节点','节点名称',nodelist[i+1][j+1][k+1][l]); 
                                }
                            } 
                        }
                    } 
                }
            }
        }
       }
       // onepathlist=conObj.split(":");
    });
    // 创建
    grunt.HtmlHandle=function(){
            var fs =require('fs');
            this.HeaderBlock=function(content,path){
               var headerBlockContent= '\n<z:config type="Block" name="页头" ></z:config>\n'; 
               var headerPath='build/'+path+'/tpl/header.template.html';
               var cheerio = require('cheerio');
               var  $= cheerio.load(content,{decodeEntities: false,xmlMode:true});
                // console.log($('.banner').html());
               var _tempContent1=$.html(".header")+'\n';
               var _tempContent2=$.html(".banner")+'\n';
               // headerBlockContent +=_tempContent1+_tempContent2;
               fs.writeFileSync(headerPath, this.replaceZyTags(headerBlockContent),['utf8','0o666','a+']);
            }
            this.FooterBlock=function(content,path){
               var headerBlockContent= '<z:config type="Block" name="页脚" ></z:config>\n'; 
               var headerPath='build/'+path+'/tpl/footer.template.html';
               var cheerio = require('cheerio');
               var  $= cheerio.load(content,{decodeEntities: false});
               // console.log($.html());
               var _tempContent1=$.html(".con066")+'\n';
               var _tempContent2=$.html(".con077")+'\n';
               headerBlockContent +=_tempContent1+_tempContent2;
               fs.writeFileSync(headerPath, this.replaceZyTags(headerBlockContent),['utf8','0o666','a+']);
            }
            this.replaceList=function(content){
                // this.content=this.content.replace(/(<title>)(.+)(<\/title>)/g,'$1'+config.name+'$3'); 
                // return content.match(/class="list"/g);
                // console.log(content);
                 var cheerio = require('cheerio');
                 var restr='';
                 var  $= cheerio.load(content,{decodeEntities: false});
                 $('ul').each(function(i, elem) {
                    var _data=$(this).attr("data");
                    var _type=_data?_data.split(",")[0]:_type;
                    var _name=_data?_data.split(",")[1]:_type;
                    var _that=$(this);
                       // console.log(_type,_name);
                    // 列表类型   1为栏目列表 2为文章列表
                     if(_type==1){
                       
                       var _c='\n';
                        $(this).find("li").each(function(i,e){
                            var _class=$(this).attr("class");
                             // console.log($(this).html());
                              _c+='\t\t\t\t<li class="'+_class+'"><cms:catalog  count="1" type="Article" name="'+$(this).text()+'"><z:list><a href="${Catalog.Link}">${Catalog.Name}</a></z:list></cms:catalog></li>\n';
                        });
                        _that.html(_c);
                    }else if(_type==2){
                       var _c='\n';
                       var _count=$(this).find("li").length;
                    
                       if($(this).find(".list-time").length){
                         _c+='\t\t\t<cms:article catalog="'+_name+'" count="'+_count+'" type="Recent" level="CurrentAndChild" >\n';
                         _c+='\t\t\t\t<z:list>\n';
                         _c+='\t\t\t\t\t<li><a href="${Article.Link}" title="${Article.Title}">${charWidth(Article.Title, 30,"...")}</a></li>\n';
                         _c+='\t\t\t\t</z:list>\n';
                         _c+=' \t\t\t</cms:article>\n';
                        _that.html(_c);
                       }else{
                         _c+='\t\t\t<cms:article catalog="'+_name+'" count="'+_count+'" type="Recent" level="CurrentAndChild" >\n';
                         _c+='\t\t\t\t<z:list>\n';
                         _c+='\t\t\t\t\t<li><a href="${Article.Link}" title="${Article.Title}">${charWidth(Article.Title, 30,"...")}</a><span>${format(Article.PublishDate,"yyyy-MM-dd")}</span></li>\n';
                         _c+='\t\t\t\t</z:list>\n';
                         _c+=' \t\t\t</cms:article>\n';
                        _that.html(_c);
                       }
                        // console.log($(this).html());

                       // restr
                    }
                });
                 // $("ul").each(function(){
                 //    if($(this).attr("data")){
                 //        console.log($(this).html()); 
                 //    }
      
                 // });
                 return this.replaceZyTags($.html());
            }
            this.changeFlash=function(content){
                // this.content=this.content.replace(/(css\/)(.+)(\.css)/g,'$1'+config.date+'$3'); 
            }
            this.replaceZyTags=function(content){
                 var a_reg=/<\/a[^>]{2,}>/g;
                 var a_arr=content.match(a_reg,content);
                 var li_reg=/<\/a[^>]{2,}>/g;
                 var li_arr=content.match(li_reg,content);
                 var list1_reg=/<\/cms\:catalog[^>]{2,}>/g;
                 var list1_arr=content.match(list1_reg,content);
                 var list2_reg=/<\/cms\:article[^>]{2,}>/g;
                 var list2_arr=content.match(list2_reg,content);
                 console.log(a_arr,li_arr,list1_arr,list2_arr);
                 var temparr=[];
                 for(var i=0;i<a_arr.length;i++){
                    
                 }
                return content;
            }

     //创建emmet原型对象 默认包含以下几种方法 
    }
    grunt.registerTask("temp","generateTemplateHtml",function(type,path){
        
        if(!path){
             grunt.log.warn('参数缺失'); 
             return false;
        }else{
             var fs =require('fs');
             var tplpath='build/'+path+'/tpl/';
              if (fs.existsSync(tplpath)) {
                    console.log('模板目录已存在 复写模板');
               } else {
                   fs.mkdirSync(tplpath);
            
                   console.log('模板目录已创建成功\n');
               }
            if(type==1){
                var hand1=new grunt.HtmlHandle();
                console.log('执行泽元模板生成任务');
                var indexContent= fs.readFileSync('build/'+path+'/html/index.html','utf8');
                // var Q=require("q");                

                // var footerBlockContent= '<z:config type="Block" name="页脚" ></z:config>';
                var indexPath='build/'+path+'/tpl/index.template.html';
                var indexNewContent;
                var cheerio = require('cheerio');
                var  $= cheerio.load(indexContent,{decodeEntities: false});
                 $(".banner").after("\n<cms:include file='header.template.html'>{ZCMS:文件包含}</cms:include>");
                 $(".con077").after("\n<cms:include file='footer.template.html'>{ZCMS:文件包含}</cms:include>");
                 // console.log($("#flash1").html(),$(".slidebox .hd li"));
                var _temp1=hand1.replaceList($.html());
                // console.log(_temp1);
                hand1.HeaderBlock(_temp1,path);
                hand1.FooterBlock(_temp1,path);

                // var _temp2=hand1.replaceZyTags(_temp1);
                // console.log(_temp2);
                // $('.list li').replaceWith('士大夫');
                // $('.list').html();
                // fs.writeFileSync(indexPath, _temp2,['utf8','0o666','a+']);

                // console.log($('.header').prop.toString());
            }
        }
    });






}
